package com.utc.cards.player.view;

import static com.utc.cards.Constants.JADE_CARDS_PREFS_FILE;

import java.util.ArrayList;
import java.util.StringTokenizer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.SeekBar;

import com.utc.cards.Constants;
import com.utc.cards.R;
import com.utc.cards.common.view.CardsContainer;
import com.utc.cards.model.card.Card;
import com.utc.cards.model.game.InfoType;
import com.utc.cards.player.jade.PlayerAgentManager;
import com.utc.cards.player.jade.agent.playerAgent.IPlayerAgent;
import com.utc.cards.utils.Utils;

public abstract class AbstractPlayerGameActivity extends Activity implements IPlayerGameActivity
{

    private static Logger log = LoggerFactory.getLogger(AbstractPlayerGameActivity.class);

    protected MyReceiver receiver;

    protected IPlayerAgent playerAgent;
    protected CardsContainer _cardsContainer;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        Utils.hideNavigationButtons(this);

        // reception des intents
        registerReceivers();

        // récupération des agents
        loadAgents();

        setContentView(getLayout());
        onCreateSpecificView(savedInstanceState);
    }

    public abstract void onCreateSpecificView(Bundle savedInstanceState);

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        log.debug("onDestroy()... unregister receiver");
        unregisterReceiver(receiver);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(getMenu(), menu);
        return true;
    }

    @Override
    abstract public boolean onOptionsItemSelected(MenuItem item);

    private void loadAgents()
    {
        SharedPreferences settings = getSharedPreferences(JADE_CARDS_PREFS_FILE, Context.MODE_PRIVATE);
        String name = settings.getString(Constants.GMAIL, "");

        playerAgent = PlayerAgentManager.instance().getAgent(this, Constants.CARDS_PLAYER_AGENT_NAME + "-" + name, IPlayerAgent.class);
        log.debug("onCreate() : agent chargés pour l'activity de JEU: " + playerAgent);
    }

    private class MyReceiver extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();
            log.info("Received intent " + action);
            if (action.equalsIgnoreCase(Constants.POP_INFO))
            {
                Utils.showAlertDialog(getThis(), intent.getStringExtra(InfoType.INFO.name()), false);
            }
            else if (action.equalsIgnoreCase(Constants.PLAYER_TURN) || action.equalsIgnoreCase(Constants.PLAYER_TURN_STOP))
            {
                myTurnToPlay();
            }
            else if (action.equalsIgnoreCase(Constants.CARDS_CHANGED))
            {
                // drawGameCards();

                String cardsIDs = intent.getStringExtra(Constants.CARDS_IDS);
                ArrayList<Card> cards = new ArrayList<Card>();
                if (cardsIDs != null)
                {
                    StringTokenizer st = new StringTokenizer(cardsIDs);

                    while (st.hasMoreTokens())
                    {
                        int id = Integer.parseInt(st.nextToken("|"));
                        Card card = playerAgent.getModel().getGame().getDeck().getCardByResourceId(id);
                        cards.add(card);
                    }
                }
                InfoType updateType = (InfoType) intent.getSerializableExtra(Constants.UPDATE_VIEW_TYPE);

                switch (updateType)
                {
                case ADD_CARDS:
                    if (cards.size() > 0)
                    {
                        for (Card c : cards)
                        {
                            _cardsContainer.addCard(c);
                        }
                    }
                    break;
                case REMOVE_CARDS:
                    if (cards.size() > 0)
                    {
                        for (Card c : cards)
                        {
                            _cardsContainer.removeCard(c);
                        }
                    }
                    break;
                case SET_CARDS:
                    if (cards.size() > 0)
                    {
                        _cardsContainer.setCards(cards);
                    }
                    break;
                case CLEAR_CARDS:
                    _cardsContainer.removeAllCards();
                    break;
                default:
                    break;
                }

            }
            else if (action.equalsIgnoreCase(Constants.ADVICE))
            {
                int cardID = Integer.parseInt(intent.getStringExtra(Constants.CARD_ID));

                Card card = playerAgent.getModel().getGame().getDeck().getCardByResourceId(cardID);
                if (card != null)
                {
                    SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
                    seekBar.setProgress(50);
                    String s = card.getName();
                    _cardsContainer.centerCard(s);
                }
            }
        }
    }

    private void registerReceivers()
    {
        receiver = new MyReceiver();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.POP_INFO);
        intentFilter.addAction(Constants.PLAYER_TURN);
        intentFilter.addAction(Constants.PLAYER_TURN_STOP);
        intentFilter.addAction(Constants.CARDS_CHANGED);
        intentFilter.addAction(Constants.ADVICE);
        registerReceiver(receiver, intentFilter);
    }

    public abstract Activity getThis();

    public abstract int getMenu();

    public abstract int getLayout();

    public abstract void drawGameCards();

    public abstract void getScreenSize();

    public abstract void drawSendingPanel();

    public abstract void drawSeekBar();

    public abstract void myTurnToPlay();
}
